<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="ES6," />





  <link rel="alternate" href="/atom.xml" title="OBKoro1's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="let和const是 ES6 新增的命令，用于声明变量，这两个命令跟 ES5 的var有许多不同，并且let和const也有一些细微的不同，再认真阅读了阮一峰老师的文档后，发现还是有一些不知道的细节…">
<meta name="keywords" content="ES6">
<meta property="og:type" content="article">
<meta property="og:title" content="var和let&#x2F;const的区别">
<meta property="og:url" content="http://yoursite.com/2019/01/01/var和let-const的区别/index.html">
<meta property="og:site_name" content="OBKoro1&#39;s Blog">
<meta property="og:description" content="let和const是 ES6 新增的命令，用于声明变量，这两个命令跟 ES5 的var有许多不同，并且let和const也有一些细微的不同，再认真阅读了阮一峰老师的文档后，发现还是有一些不知道的细节…">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1?raw=true">
<meta property="og:updated_time" content="2019-07-20T06:55:39.065Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="var和let&#x2F;const的区别">
<meta name="twitter:description" content="let和const是 ES6 新增的命令，用于声明变量，这两个命令跟 ES5 的var有许多不同，并且let和const也有一些细微的不同，再认真阅读了阮一峰老师的文档后，发现还是有一些不知道的细节…">
<meta name="twitter:image" content="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1?raw=true">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2019/01/01/var和let-const的区别/"/>





  <title>var和let/const的区别 | OBKoro1's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?64d57d0b926bbd27431daa89d2e0a76b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">OBKoro1's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-前端算法">
          <a href="/arithmetic/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            前端算法
          </a>
        </li>
      
        
        <li class="menu-item menu-item-博客最新更新">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            博客最新更新
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/01/01/var和let-const的区别/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="OBKoro1">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/hand1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="OBKoro1's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">var和let/const的区别</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-01-01T14:35:03+08:00">
                2019-01-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/ES6/" itemprop="url" rel="index">
                    <span itemprop="name">ES6</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2019/01/01/var和let-const的区别/" class="leancloud_visitors" data-flag-title="var和let/const的区别">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,725 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  7分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1?raw=true" alt=""></p>
<p><code>let</code>和<code>const</code>是 ES6 新增的命令，用于声明变量，这两个命令跟 ES5 的<code>var</code>有许多不同，并且<code>let</code>和<code>const</code>也有一些细微的不同，再认真阅读了阮一峰老师的<a href="http://es6.ruanyifeng.com/#docs/let" target="_blank" rel="noopener">文档</a>后，发现还是有一些不知道的细节…</p>
<a id="more"></a>
<blockquote>
<p><a href="http://obkoro1.com/" target="_blank" rel="noopener">博客</a>、<a href="http://obkoro1.com/web_accumulate/accumulate/" target="_blank" rel="noopener">前端积累文档</a>、<a href="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1631b6f52f7e7015.jpeg?raw=true" target="_blank" rel="noopener">公众号</a>、<a href="https://github.com/OBKoro1" target="_blank" rel="noopener">GitHub</a></p>
</blockquote>
<h2 id="内容："><a href="#内容：" class="headerlink" title="内容："></a>内容：</h2><p><strong><code>var</code>和<code>let</code>/<code>const</code>的区别</strong></p>
<ol>
<li><p>块级作用域</p>
</li>
<li><p>不存在变量提升</p>
</li>
<li><p>暂时性死区</p>
</li>
<li><p>不可重复声明</p>
</li>
<li><p>let、const声明的全局变量不会挂在顶层对象下面</p>
</li>
</ol>
<p><strong><code>const</code>命令两个注意点:</strong></p>
<ol>
<li><p>const 声明之后必须马上赋值，否则会报错</p>
</li>
<li><p>const 简单类型一旦声明就不能再更改，复杂类型(数组、对象等)指针指向的地址不能更改，内部数据可以更改。</p>
</li>
</ol>
<h3 id="为什么需要块级作用域"><a href="#为什么需要块级作用域" class="headerlink" title="为什么需要块级作用域?"></a>为什么需要块级作用域?</h3><p>ES5只有全局作用域和函数作用域，没有块级作用域。</p>
<p>这带来很多不合理的场景:</p>
<ol>
<li>内层变量可能覆盖外层变量</li>
<li>用来计数的循环变量泄露为全局变量</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> tmp = <span class="keyword">new</span> <span class="built_in">Date</span>();</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(tmp); <span class="comment">// 想打印外层的时间作用域</span></span><br><span class="line">  <span class="keyword">if</span> (<span class="literal">false</span>) &#123;</span><br><span class="line">    <span class="keyword">var</span> tmp = <span class="string">'hello world'</span>; <span class="comment">// 这里声明的作用域为整个函数</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line">f(); <span class="comment">// undefined</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> s = <span class="string">'hello'</span>;</span><br><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; s.length; i++) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(s[i]); <span class="comment">// i应该为此次for循环使用的变量</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(i); <span class="comment">// 5 全局范围都可以读到</span></span><br></pre></td></tr></table></figure>
<h3 id="块级作用域"><a href="#块级作用域" class="headerlink" title="块级作用域"></a>块级作用域</h3><ol>
<li>作用域</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f1</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> n = <span class="number">5</span>;</span><br><span class="line">  <span class="keyword">if</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">    <span class="keyword">let</span> n = <span class="number">10</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(n); <span class="comment">// 10 内层的n</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(n); <span class="comment">// 5 当前层的n</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="2">
<li>块级作用域任意嵌套</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;&#123;&#123;</span><br><span class="line">  &#123;<span class="keyword">let</span> insane = <span class="string">'Hello World'</span>&#125;</span><br><span class="line">  <span class="built_in">console</span>.log(insane); <span class="comment">// 报错 读不到子作用域的变量</span></span><br><span class="line">&#125;&#125;&#125;&#125;;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>块级作用域真正使代码分割成块了</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line"><span class="keyword">let</span> a = ...;</span><br><span class="line">...</span><br><span class="line">&#125;</span><br><span class="line">&#123;</span><br><span class="line"><span class="keyword">let</span> a = ...;</span><br><span class="line">...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>以上形式，<strong>可以用于测试一些想法，不用担心变量重名，也不用担心外界干扰</strong></p>
<h3 id="块级作用域声明函数："><a href="#块级作用域声明函数：" class="headerlink" title="块级作用域声明函数："></a>块级作用域声明函数：</h3><blockquote>
<p>在块级作用域声明函数，因为浏览器的要兼容老代码，会产生一些<a href="http://es6.ruanyifeng.com/#docs/let#%E5%9D%97%E7%BA%A7%E4%BD%9C%E7%94%A8%E5%9F%9F%E4%B8%8E%E5%87%BD%E6%95%B0%E5%A3%B0%E6%98%8E" target="_blank" rel="noopener">问题</a>！</p>
</blockquote>
<p><strong>在块级作用域声明函数，最好使用匿名函数的形式</strong>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(<span class="literal">true</span>)&#123;</span><br><span class="line">  <span class="keyword">let</span> a = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;; <span class="comment">// 作用域为块级 令声明的函数作用域范围更清晰</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>ES6 的块级作用域允许声明函数的规则，只在使用大括号的情况下成立，如果没有使用大括号，就会报错</strong>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 报错</span></span><br><span class="line"><span class="meta">'use strict'</span>;</span><br><span class="line"><span class="keyword">if</span> (<span class="literal">true</span>)</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"></span>) </span>&#123;&#125; <span class="comment">// 我们需要给if加个&#123;&#125;</span></span><br></pre></td></tr></table></figure>
<h3 id="不存在变量提升"><a href="#不存在变量提升" class="headerlink" title="不存在变量提升"></a>不存在变量提升</h3><p><strong>变量提升的现象</strong>：在同一作用域下，变量可以在声明之前使用，值为 undefined</p>
<p>ES5 时使用<code>var</code>声明变量，经常会出现变量提升的现象。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// var 的情况</span></span><br><span class="line"><span class="built_in">console</span>.log(foo); <span class="comment">// 输出undefined</span></span><br><span class="line"><span class="keyword">var</span> foo = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// let 的情况</span></span><br><span class="line"><span class="built_in">console</span>.log(bar); <span class="comment">// 报错ReferenceError</span></span><br><span class="line"><span class="keyword">let</span> bar = <span class="number">2</span>;</span><br></pre></td></tr></table></figure>
<h3 id="暂时性死区："><a href="#暂时性死区：" class="headerlink" title="暂时性死区："></a>暂时性死区：</h3><p>只要一进入当前作用域，所要使用的变量就已经存在了，但是不可获取，<strong>只有等到声明变量的那一行代码出现，才可以获取和使用该变量</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> tmp = <span class="number">123</span>; <span class="comment">// 声明</span></span><br><span class="line"><span class="keyword">if</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">  tmp = <span class="string">'abc'</span>; <span class="comment">// 报错 因为本区域有tmp声明变量</span></span><br><span class="line">  <span class="keyword">let</span> tmp; <span class="comment">// 绑定if这个块级的作用域 不能出现tmp变量</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p><strong>暂时性死区和不能变量提升的意义在于:</strong></p>
<p>为了减少运行时错误，防止在变量声明前就使用这个变量，从而导致意料之外的行为。</p>
<h3 id="不允许重复声明变量"><a href="#不允许重复声明变量" class="headerlink" title="不允许重复声明变量"></a>不允许重复声明变量</h3><blockquote>
<p>在测试时出现这种情况:<code>var a= &#39;声明&#39;;const a = &#39;不报错&#39;</code>，这种情况是因为babel在转化的时候，做了一些处理，在浏览器的控制台中测试，就成功报错</p>
</blockquote>
<p><code>let</code>、<code>const</code>不允许在相同作用域内，重复声明同一个变量</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">func</span>(<span class="params">arg</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> arg; <span class="comment">// 报错</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">func</span>(<span class="params">arg</span>) </span>&#123;</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">let</span> arg; <span class="comment">// 不报错</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="let、const声明的全局变量不会挂在顶层对象下面"><a href="#let、const声明的全局变量不会挂在顶层对象下面" class="headerlink" title="let、const声明的全局变量不会挂在顶层对象下面"></a>let、const声明的全局变量不会挂在顶层对象下面</h3><ol>
<li>浏览器环境顶层对象是: <code>window</code></li>
<li>node环境顶层对象是: <code>global</code></li>
<li>var声明的全局变量会挂在顶层对象下面，而let、const不会挂在顶层对象下面。如下面这个栗子</li>
</ol>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="comment">// 如果在 Node环境，可以写成 global.a</span></span><br><span class="line"><span class="comment">// 或者采用通用方法，写成 this.a</span></span><br><span class="line"><span class="built_in">window</span>.a <span class="comment">// 1</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> b = <span class="number">1</span>;</span><br><span class="line"><span class="built_in">window</span>.b <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>
<h2 id="const命令"><a href="#const命令" class="headerlink" title="const命令"></a>const命令</h2><ol>
<li><p><strong>一旦声明，必须马上赋值</strong></p>
 <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> p; <span class="keyword">var</span> p1; <span class="comment">// 不报错</span></span><br><span class="line"><span class="keyword">const</span> p3 = <span class="string">'马上赋值'</span></span><br><span class="line"><span class="keyword">const</span> p3; <span class="comment">// 报错 没有赋值</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><strong>const一旦声明值就不能改变</strong></p>
<h4 id="简单类型-不能改动"><a href="#简单类型-不能改动" class="headerlink" title="简单类型:不能改动"></a>简单类型:不能改动</h4> <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p = <span class="string">'不能改变'</span>;</span><br><span class="line">p = <span class="string">'报错'</span></span><br></pre></td></tr></table></figure>
<h4 id="复杂类型-变量指针不能变"><a href="#复杂类型-变量指针不能变" class="headerlink" title="复杂类型:变量指针不能变"></a>复杂类型:变量指针不能变</h4><p> 考虑如下情况：</p>
 <figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p = [<span class="string">'不能改动'</span>]</span><br><span class="line"><span class="keyword">const</span> p2 = &#123;</span><br><span class="line">  name: <span class="string">'OBKoro1'</span></span><br><span class="line">&#125;</span><br><span class="line">p[<span class="number">0</span>] = <span class="string">'不报错'</span></span><br><span class="line">p2.name = <span class="string">'不报错'</span></span><br><span class="line">p = [<span class="string">'报错'</span>]</span><br><span class="line">p2 = &#123;</span><br><span class="line">  name: <span class="string">'报错'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p> const所说的一旦声明值就不能改变，实际上指的是：<strong>变量指向的那个内存地址所保存的数据不得改动</strong></p>
<ul>
<li>简单类型(number、string、boolean)：<strong>内存地址就是值,即常量(一变就报错)</strong>.</li>
<li><p>复杂类型(对象、数组等)：<strong>地址保存的是一个指针，<code>const</code>只能保证指针是固定的(总是指向同一个地址),它内部的值是可以改变的(不要以为const就安全了！)</strong></p>
<p> 所以只要不重新赋值整个数组/对象， 因为保存的是一个指针，所以对数组使用的<code>push</code>、<code>shift</code>、<code>splice</code>等方法也是允许的，你就是把值一个一个全都删光了都不会报错。</p>
<blockquote>
<p>复杂类型还有函数，正则等，这点也要注意一下。</p>
</blockquote>
</li>
</ul>
</li>
</ol>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结:"></a>总结:</h2><p>再总结一下，看到这些名词，脑子里应该会有对应的理解，如果没有的话，那可以再看看对应的内容。</p>
<h3 id="var和let-const的区别"><a href="#var和let-const的区别" class="headerlink" title="var和let/const的区别:"></a><code>var</code>和<code>let</code>/<code>const</code>的区别:</h3><ol>
<li>块级作用域</li>
<li>不存在变量提升</li>
<li>暂时性死区</li>
<li>不可重复声明</li>
<li>let、const声明的全局变量不会挂在顶层对象下面</li>
</ol>
<h3 id="const命令两个注意点"><a href="#const命令两个注意点" class="headerlink" title="const命令两个注意点:"></a><code>const</code>命令两个注意点:</h3><ol>
<li><p><code>let</code>可以先声明稍后再赋值,而<code>const</code>在 声明之后必须马上赋值，否则会报错</p>
</li>
<li><p>const 简单类型一旦声明就不能再更改，复杂类型(数组、对象等)指针指向的地址不能更改，内部数据可以更改。</p>
</li>
</ol>
<h3 id="let、const使用场景"><a href="#let、const使用场景" class="headerlink" title="let、const使用场景:"></a>let、const使用场景:</h3><ol>
<li><code>let</code>使用场景：变量，用以替代<code>var</code>。</li>
<li><code>const</code>使用场景：常量、声明匿名函数、箭头函数的时候。</li>
</ol>
<h3 id="鼓励我一下："><a href="#鼓励我一下：" class="headerlink" title="鼓励我一下："></a>鼓励我一下：</h3><p>觉得还不错的话，给我的项目点个<a href="https://github.com/OBKoro1/Brush_algorithm" target="_blank" rel="noopener">star</a>吧</p>
<p><a href="http://obkoro1.com/" target="_blank" rel="noopener">博客</a>、<a href="http://obkoro1.com/web_accumulate/accumulate/" target="_blank" rel="noopener">前端积累文档</a>、<a href="https://raw.githubusercontent.com/OBKoro1/articleImg_src/master/juejin/1631b6f52f7e7015.jpeg?raw=true" target="_blank" rel="noopener">公众号</a>、<a href="https://github.com/OBKoro1" target="_blank" rel="noopener">GitHub</a></p>
<p>参考资料：</p>
<p><a href="http://es6.ruanyifeng.com/#docs/let" target="_blank" rel="noopener">let 和 const 命令</a></p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>听说，打赏我的人最后都找到了真爱。</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/weixin.jpg" alt="OBKoro1 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/ali.jpg" alt="OBKoro1 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/ES6/" rel="tag"><i class="fa fa-tag"></i> ES6</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/12/18/轻松掌握浏览器重绘重排原理/" rel="next" title="轻松掌握浏览器重绘重排原理">
                <i class="fa fa-chevron-left"></i> 轻松掌握浏览器重绘重排原理
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/01/01/Vuex-的使用入门-极简使用/" rel="prev" title="Vuex的使用入门-极简使用">
                Vuex的使用入门-极简使用 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image"
              src="/uploads/hand1.jpg"
              alt="OBKoro1" />
          
            <p class="site-author-name" itemprop="name">OBKoro1</p>
            <p class="site-description motion-element" itemprop="description">种一棵树最好的时间是十年前,其次是现在</p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives">
            
                <span class="site-state-item-count">105</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">74</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/OBKoro1" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>GitHub</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-globe"></i>掘金</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://obkoro1.com/web_accumulate/" target="_blank" title="前端积累">
                  
                    <i class="fa fa-fw fa-globe"></i>前端积累</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://segmentfault.com/u/obkoro1/articles" target="_blank" title="segmentfault">
                  
                    <i class="fa fa-fw fa-globe"></i>segmentfault</a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#内容："><span class="nav-number">1.</span> <span class="nav-text">内容：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#为什么需要块级作用域"><span class="nav-number">1.1.</span> <span class="nav-text">为什么需要块级作用域?</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#块级作用域"><span class="nav-number">1.2.</span> <span class="nav-text">块级作用域</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#块级作用域声明函数："><span class="nav-number">1.3.</span> <span class="nav-text">块级作用域声明函数：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不存在变量提升"><span class="nav-number">1.4.</span> <span class="nav-text">不存在变量提升</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#暂时性死区："><span class="nav-number">1.5.</span> <span class="nav-text">暂时性死区：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不允许重复声明变量"><span class="nav-number">1.6.</span> <span class="nav-text">不允许重复声明变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#let、const声明的全局变量不会挂在顶层对象下面"><span class="nav-number">1.7.</span> <span class="nav-text">let、const声明的全局变量不会挂在顶层对象下面</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#const命令"><span class="nav-number">2.</span> <span class="nav-text">const命令</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#简单类型-不能改动"><span class="nav-number">2.0.1.</span> <span class="nav-text">简单类型:不能改动</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#复杂类型-变量指针不能变"><span class="nav-number">2.0.2.</span> <span class="nav-text">复杂类型:变量指针不能变</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#总结"><span class="nav-number">3.</span> <span class="nav-text">总结:</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#var和let-const的区别"><span class="nav-number">3.1.</span> <span class="nav-text">var和let/const的区别:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#const命令两个注意点"><span class="nav-number">3.2.</span> <span class="nav-text">const命令两个注意点:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#let、const使用场景"><span class="nav-number">3.3.</span> <span class="nav-text">let、const使用场景:</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#鼓励我一下："><span class="nav-number">3.4.</span> <span class="nav-text">鼓励我一下：</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 &mdash; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">OBKoro1</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">
      156.0k
    </span>
  
</div>




<div>
<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span class="site-uv"><i class="fa fa-user"></i> 访问用户： <span class="busuanzi-value" id="busuanzi_value_site_uv">21621</span> 人 </span>
<span class="site-pv"><i class="fa fa-eye"></i> 访问次数： <span class="busuanzi-value" id="busuanzi_value_site_pv">68503</span> 次</span>

</div>



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("9ANFp60h6oVyxIPGlau3NOA4-gzGzoHsz", "tMdNuKMbFtN4QsekeNVu83TV");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>

